/**
 *Copyright (c) 2024 watereyes
 * workflow is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.workflow.api.listener;

import java.util.ArrayList;
import java.util.List;

import org.activiti.engine.delegate.event.ActivitiEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.koron.workflow.common.exception.WorkflowException;

public class ProcessEventListenerDispatcher {
	
	private static Logger log = LoggerFactory.getLogger(ProcessEventListenerDispatcher.class);

	private static final List<IPorcessListener> LISTENER = new ArrayList<IPorcessListener>();
	
	private static  ProcessEventListenerDispatcher DISPATCHER;

	private ProcessEventListenerDispatcher() {
		LISTENER.add(new ProcessCreatedListener());
		LISTENER.add(new TaskCreatedListener());
		LISTENER.add(new TaskRejectCreatedListener());
		LISTENER.add(new TaskCompletedListener());
		LISTENER.add(new TaskAssigendListener());
		LISTENER.add(new ActivityStartedListener());
		LISTENER.add(new ProcessSuspendListener());
		LISTENER.add(new ProcessCompletedListener());
		LISTENER.add(new ProcessActivateListener());
		LISTENER.add(new ProcessDeleteListener());
	}

	public static ProcessEventListenerDispatcher getInstance() {
		if(null==DISPATCHER){
			DISPATCHER=new ProcessEventListenerDispatcher();
		}
		return DISPATCHER;
	}

	public void dispatchEvent(ActivitiEvent event) {
		try {
			for (IPorcessListener listener : LISTENER) {
				switch (event.getType()) {
					case PROCESS_COMPLETED: {
						listener.processCompleted(event);
						break;
					}
					case PROCESS_STARTED: {
						listener.processCreated(event);
						break;
					}
					case TASK_CREATED: {
						listener.taskCreatetd(event);
						break;
					}
					case TASK_COMPLETED: {
						listener.taskCompleted(event);
						break;
					}
					case TASK_ASSIGNED: {
						listener.tastAssigned(event);
						break;
					}
					case ENTITY_SUSPENDED :{
						listener.processSuspend(event);
						break;
					}
					case PROCESS_CANCELLED :{
						listener.processDelete(event);
						break;
					}
					case ENTITY_ACTIVATED :{
						listener.processActivated(event);
						break;
					}
					case ACTIVITY_STARTED :{
						listener.activityStarted(event);
						break;
					}
					default: {
						break;
					}
				}
			}
		}catch(Exception ex) {
			log.error("流程监听器执行失败!原因{}", ex.getMessage());
			throw new WorkflowException(ex);
		}
	}
}
